<template>
  <div class="route-manage-page">
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <a-input-search
        v-model:value="searchValue"
        placeholder="搜索路线名称"
        enter-button="搜索"
        size="large"
        allow-clear
        @search="onSearch"
        style="max-width: 400px"
      />
      <a-button type="primary" size="large" @click="showAddModal" :icon="h(PlusOutlined)">
        添加路线
      </a-button>
    </div>

    <!-- 路线列表 -->
    <div class="route-list">
      <div v-if="routeVOs.length > 0" class="route-cards">
        <RouteCard
          v-for="(route, index) in routeVOs"
          :key="route.id || index"
          :route="route"
          @click="showRouteInfo"
        />
      </div>
      <div v-else class="no-routes">
        <a-empty description="暂无路线数据">
          <a-button type="primary" @click="showAddModal">添加第一条路线</a-button>
        </a-empty>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="routeVOs.length > 0">
      <a-pagination
        v-model:current="pagination.current"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :show-total="
          (total: number, range: [number, number]) =>
            `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
        "
        :show-size-changer="true"
        :show-quick-jumper="true"
        :page-size-options="['6', '12', '18', '24']"
        @change="handlePageChange"
        @showSizeChange="handlePageSizeChange"
      />
    </div>

    <!-- 添加路线模态框 -->
    <a-modal
      v-model:open="isAddModalVisible"
      title="添加路线"
      @cancel="handleAddCancel"
      :footer="null"
      width="900px"
      :destroy-on-close="true"
    >
      <AddRouteForm @success="handleAddSuccess" @cancel="handleAddCancel" />
    </a-modal>

    <!-- 路线详情模态框 -->
    <a-modal
      v-model:open="isInfoModalVisible"
      title="路线详情"
      @cancel="handleInfoCancel"
      :footer="null"
      width="1200px"
      :destroy-on-close="true"
    >
      <RouteInfo
        v-if="selectedRoute"
        :route-data="selectedRoute"
        @updated="handleRouteUpdated"
        @deleted="handleRouteDeleted"
      />
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, h, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { getListRouteVo } from '@/api/routeController'
import AddRouteForm from '@/components/AddRouteForm.vue'
import RouteInfo from '@/components/RouteInfo.vue'
import RouteCard from '@/components/RouteCard.vue'

const routeVOs = ref<API.RouteVO[]>([])
const searchValue = ref<string>('')
const isAddModalVisible = ref<boolean>(false)
const isInfoModalVisible = ref<boolean>(false)
const selectedRoute = ref<API.RouteVO | null>(null)

// 分页相关状态
const pagination = ref({
  current: 1,
  pageSize: 6,
  total: 0,
})

// 获取路线数据
const fetchData = async (params: API.getListRouteVOParams = {}) => {
  try {
    // 根据后端 RouteQueryRequest 的结构构建参数
    const requestParams = {
      // 分页参数
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
      // 查询参数
      ...params,
    }

    console.log('🔍 请求路线分页参数:', requestParams)
    const res = await getListRouteVo(requestParams)
    console.log('🔍 API完整响应:', res)
    console.log('🔍 响应数据结构:', res.data)

    if (res.data.code === 200 && res.data.data) {
      const pageData = res.data.data
      console.log('🔍 分页数据详情:', pageData)
      console.log('🔍 路线记录数组:', pageData.records)
      console.log('🔍 总数:', pageData.total)
      console.log('🔍 当前页:', pageData.current)
      console.log('🔍 页大小:', pageData.size)

      routeVOs.value = pageData.records ?? []
      pagination.value.total = parseInt(pageData.total ?? '0')
      pagination.value.current = parseInt(pageData.current ?? '1')
      pagination.value.pageSize = parseInt(pageData.size ?? '6')

      console.log('✅ 解析后的路线列表:', routeVOs.value)
      console.log('✅ 解析后的分页信息:', pagination.value)

      // 检查每个路线对象的字段
      if (routeVOs.value.length > 0) {
        console.log('🔍 第一个路线对象详情:', {
          id: routeVOs.value[0].id,
          routeName: routeVOs.value[0].routeName,
          routeInfo: routeVOs.value[0].routeInfo,
          spendTime: routeVOs.value[0].spendTime,
          suitableTime: routeVOs.value[0].suitableTime,
          routeCoverImage: routeVOs.value[0].routeCoverImage,
          alongScenics: routeVOs.value[0].alongScenics,
          routeTags: routeVOs.value[0].routeTags,
          routeStatus: routeVOs.value[0].routeStatus,
          userAccount: routeVOs.value[0].userAccount,
          createTime: routeVOs.value[0].createTime,
          updateTime: routeVOs.value[0].updateTime,
        })
      }
    } else {
      console.warn('⚠️ API响应异常:', res.data)
      message.warning('获取路线数据异常: ' + (res.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('❌ 获取路线数据失败:', error)
    message.error('获取路线数据失败')
  }
}

// 搜索路线
const onSearch = async (searchValue: string) => {
  pagination.value.current = 1 // 搜索时重置到第一页
  await fetchData({ routeName: searchValue })
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  console.log('分页变化:', { page, pageSize })
  pagination.value.current = page
  pagination.value.pageSize = pageSize
  fetchData({ routeName: searchValue.value || undefined })
}

// 处理每页条数变化
const handlePageSizeChange = (current: number, size: number) => {
  console.log('每页条数变化:', { current, size })
  pagination.value.current = 1 // 改变每页条数时重置到第一页
  pagination.value.pageSize = size
  fetchData({ routeName: searchValue.value || undefined })
}

// 显示添加路线模态框
const showAddModal = () => {
  isAddModalVisible.value = true
}

// 显示路线详情模态框
const showRouteInfo = (route: API.RouteVO) => {
  console.log('点击了路线卡片:', route)
  selectedRoute.value = route
  isInfoModalVisible.value = true
}

// 处理添加路线取消
const handleAddCancel = () => {
  isAddModalVisible.value = false
}

// 处理路线详情关闭
const handleInfoCancel = () => {
  isInfoModalVisible.value = false
  selectedRoute.value = null
}

// 处理添加路线成功事件
const handleAddSuccess = async () => {
  console.log('路线添加成功，正在刷新数据...')
  isAddModalVisible.value = false
  await fetchData() // 重新获取数据
  message.success('路线添加成功！')
}

// 处理路线更新事件
const handleRouteUpdated = async (updatedRoute: API.RouteVO, needRefresh = false) => {
  console.log('路线更新成功，需要刷新:', needRefresh)

  if (needRefresh) {
    // 如果上传了新图片，重新获取数据以确保图片URL正确
    console.log('🔄 图片已更新，重新获取路线数据...')
    await fetchData()

    // 重新找到更新后的路线并设置为选中状态
    const refreshedRoute = routeVOs.value.find((route) => route.id === updatedRoute.id)
    if (refreshedRoute) {
      selectedRoute.value = refreshedRoute
      console.log('✅ 已更新选中路线为最新数据')
    }

    message.success('路线信息和图片已更新！')
  } else {
    // 只是普通字段更新，直接更新本地数据
    const index = routeVOs.value.findIndex((route) => route.id === updatedRoute.id)
    if (index !== -1) {
      routeVOs.value[index] = updatedRoute
    }

    // 更新选中的路线数据
    selectedRoute.value = updatedRoute

    message.success('路线信息已更新！')
  }
}

// 处理路线删除事件
const handleRouteDeleted = async (routeId: number) => {
  console.log('路线删除成功，ID:', routeId)

  // 关闭详情模态框
  isInfoModalVisible.value = false
  selectedRoute.value = null

  // 重新获取数据
  await fetchData()

  message.success('路线删除成功！')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.route-manage-page {
  padding: 24px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 0;
}

.route-list {
  margin-bottom: 24px;
}

.route-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.no-routes {
  text-align: center;
  padding: 60px 20px;
  background: #fafafa;
  border-radius: 12px;
  border: 1px dashed #d9d9d9;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    gap: 16px;
  }

  .route-cards {
    grid-template-columns: 1fr;
  }

  .pagination-container {
    padding: 8px;
  }
}

@media (max-width: 1200px) {
  .route-cards {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}
</style>
